#!/usr/bin/env python

import nltk


def gender_features(word):
	# return {'suffix1':word[-1],'suffix2':word[-2]}
	return {'suffix1':word[-1]}

# prepare data
from nltk.corpus import names
labeled_name = [(name,'male') for name in names.words('male.txt')] +\
	[(name,'female') for name in names.words('female.txt')]

import random
random.shuffle(labeled_name)

train_names = labeled_name[1500:]
devtest_names = labeled_name[500:1500]
test_names = labeled_name[:500]

train_set = [(gender_features(name),gender) for (name,gender) in train_names ]
devtest_set = [(gender_features(name),gender) for (name,gender) in devtest_names ]
test_set = [(gender_features(name),gender) for (name,gender) in test_names ]

classifier = nltk.NaiveBayesClassifier.train(train_set)
errors = []
for (name, tag) in devtest_names:
	guess = classifier.classify(gender_features(name))
	if guess!= tag:
		errors.append((tag,guess,name))
for (tag, guess, name) in sorted(errors):
	print('correct={:<8} guess={:<8s} name={:<30}'.format(tag, guess, name))

print(nltk.classify.accuracy(classifier, devtest_set))